<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议 https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\admin\traits;

use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\facade\Db;

/**
 * 后台CURD复用
 * Trait Curd
 *
 * @package app\admin\traits
 */
trait Curd
{

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if (input('selectFields')) {
            return $this->selectList();
        }
        list ($page, $limit, $where) = $this->buildTableParames();
        $count = $this->model->where($where)->count();
        $list = $this->model->where($where)
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        
        return msg([
            'list' => $list,
            'count' => $count
        ], 0, "success");
    }

    /**
     * @NodeAnotation(title="详情")
     */
    public function info()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return msg([], 1, "数据不存在");
        }
        
        return msg($row, 0, "success");
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $post = $this->request->post();
        $rule = [];
        $this->validate($post, $rule);
        try {
            $save = $this->model->save($post);
        } catch (\Exception $e) {
            return msg([], 1, "保存异常" . $e->getMessage());
        }
        return $save ? msg([], 0, "保存成功") : msg([], 1, "保存失败");
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $post = $this->request->post();
        $id = $post['id'];
        $row = $this->model->find($id);
        if (empty($row)) {
            return msg([], 1, "数据不存在");
        }
        
        $rule = [];
        $this->validate($post, $rule);
        try {
            $save = $row->save($post);
        } catch (\Exception $e) {
            return msg([], 1, "保存异常" . $e->getMessage());
        }
        return $save ? msg([], 0, "保存成功") : msg([], 1, "保存失败");
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        if ($row->isEmpty()) {
            return msg([], 1, "数据不存在");
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            return msg([], 1, "删除异常" . $e->getMessage());
        }
        return $save ? msg([], 0, "删除成功") : msg([], 1, "删除失败");
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list ($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = ! empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (! in_array($vo['Field'], $this->noExportFields)) {
                $header[] = [
                    $comment,
                    $vo['Field']
                ];
            }
        }
        $list = $this->model->where($where)
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (! $row) {
            return msg([], 1, "数据不存在");
        }
        if (! in_array($post['field'], $this->allowModifyFields)) {
            return msg([], 1, '该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value']
            ]);
        } catch (\Exception $e) {
            return msg([], 1, "操作异常" . $e->getMessage());
        }
        return msg([], 0, "保存成功");
    }
}
